package com.sencorsta.ids.robot.common;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.http.HttpHandler;
import com.sencorsta.ids.robot.userSimulation.GameSimUser;
import com.sencorsta.ids.robot.userSimulation.SimulationCenter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.HashSet;
import java.util.Iterator;

import java.util.Set;

/**
 * @author TAO
 * @description: 机器人房间刷新
 * @date 2020/1/4 19:24
 */
public class SimRefreshRoom extends HttpHandler {
    @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("--------------------机器人房间刷新-----SimRefreshRoom--------------------");


        int type=params.getInteger("type");//离开类型  0，全房间离开  1，部分离开
        int roomId=params.getInteger("roomId");//房间Id
        int gameId=params.getInteger("gameId");//游戏Id

        if (type==0){
            //离开的机器人set
            Set<GameSimUser> outSimUser = new HashSet<>();
            for (var simulation : SimulationCenter.simulationUserMap.keySet()) {
                GameSimUser gameSimUser = (GameSimUser) SimulationCenter.simulationUserMap.get(simulation);
                if (gameSimUser.isInRoom) {//得到要离开房间的机器人
                    outSimUser.add(gameSimUser);//得到离开的机器人
                }
            }
            if (outSimUser.size() == 0) {
                return error(ErrorCodeList.OUT_SIMULATION_IS_NULL);
            }

            Iterator<GameSimUser> it = outSimUser.iterator();
            while (it.hasNext()) {
                it.next().leaveRoom();
                it.remove();//将当前添加的机器人在可用机器人set中移除
            }
        }else{
            Set<GameSimUser> outSimUser=new HashSet<>();
            for (var simulation: SimulationCenter.simulationUserMap.keySet()){
                GameSimUser gameSimUser=(GameSimUser)SimulationCenter.simulationUserMap.get(simulation);
                if (gameSimUser.gameId==gameId&&gameSimUser.roomId==roomId){//得到要离开房间的机器人
                    outSimUser.add(gameSimUser);//得到离开的机器人
                }
            }
            if (outSimUser.size()==0){
                return error(ErrorCodeList.OUT_SIMULATION_IS_NULL);
            }
            Iterator<GameSimUser> it = outSimUser.iterator();
            while (it.hasNext()){
                it.next().leaveRoom();
                it.remove();//将当前添加的机器人在可用机器人set中移除
            }

        }

        return success();
    }

    @Override
    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return doPost(ctx, request, params);
    }

    @Override
    public String getPath() {
        return "/Robot/SimRefreshRoom";
    }
}
